package com.app.redis;

import java.util.concurrent.Semaphore;

public class ReleaseExample {
    private static final Semaphore semaphore = new Semaphore(2); // 定义2个许可

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Task()).start();
        }
    }

    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " 尝试获取许可");
                semaphore.acquire(); // 获取许可
                System.out.println(Thread.currentThread().getName() + " 获取到许可，开始执行任务");
                Thread.sleep(1000); // 模拟任务执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + " 任务执行完毕，释放许可");
                semaphore.release(); // 释放许可
            }
        }
    }
}